﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HSDc.DefinitionTransformer.Controller
{
    public class TransformController
    {
        private Entity.Process _proc;
        public void CommitTransform(DTO.ProcessDefinition procDef) 
        {
            TransferDtoValue(procDef);
            HSDc.DefinitionTransformer.Entity.Transform tran = new DefinitionTransformer.Entity.Transform();
            tran.Commit(_proc);
        
        }

        public DTO.ProcessDefinition TransformDiagram(int diagramId, string resourceId)
        {
            HSDc.DefinitionTransformer.Entity.Transform tran = new DefinitionTransformer.Entity.Transform();
            _proc = tran.Excute(diagramId, resourceId);
            return TransferToDto(_proc);
        }

        private DTO.ProcessDefinition TransferToDto(Entity.Process proc) 
        {

            DTO.ProcessDefinition procDef = new DTO.ProcessDefinition();

            foreach (Entity.Swimlane s in proc.Swimlanes)
            {
                DTO.Swimlane ds = new DTO.Swimlane();
                ds.Id = s.Id;
                ds.Seq = s.SeqNo;
                ds.Name = s.Name;
                procDef.Swimlanes.Add(ds);
            }


            foreach (Entity.ProcessElement el in proc.ConnectedElements)
            {
                if (el.GetType() == typeof(Entity.Decision))
                {
                    DTO.Decisioin dec = new DTO.Decisioin();
                    dec.Id = el.Id;
                    dec.Name = el.Name;
                    procDef.Decisions.Add(dec);
                }
            }

            return procDef;
        }

        private void TransferDtoValue(DTO.ProcessDefinition procDef) 
        {
            _proc.Name = procDef.Name;
            _proc.Version = procDef.Version;
            _proc.Active = procDef.Active;
            _proc.Status = Convert.ToInt32(_proc.Active);


            foreach (DTO.Swimlane s in procDef.Swimlanes)
            {
                var result = from sw in _proc.Swimlanes where sw.Id == s.Id && sw.SeqNo == s.Seq select sw;
                foreach (var item in result)
                    item.RuleClass = s.RuleClass;
 
            }

            foreach (DTO.Decisioin d in procDef.Decisions)
            {
                var result = from e in _proc.ConnectedElements where e.Id ==d.Id  select e;
                foreach (var item in result)
                    ((Entity.Decision)item).RuleClass = d.RuleClass;
 
            }
        
        }

    }
}
